import request from './request'

export default function(options) {
	options = Object.assign({}, options, {
		type: 'POST',
		contentType: false,
		processData: false,
		xhrFields: {// 这样在请求的时候会自动将浏览器中的cookie发送给后台
			withCredentials: true
		},
	});

	const file = options.file,
		fileFieldName = options.name;

	options.data = resolveFormData(options.data);
	options.data.append(fileFieldName, file);
	const csrfToken = $('meta[name="csrf-token"]').attr('content');
	if (csrfToken) {
		options.data.append('_token', csrfToken);
	}

	const chain = [].concat(request.interceptors.request, [{
		fulfilled: () => {
			return $.ajax(options).then((res, _, XMLHttpRequest) => {
				XMLHttpRequest.data = res;
				XMLHttpRequest.config = options;
				return $.Deferred().resolve(XMLHttpRequest);
			}, (XMLHttpRequest) => {
				XMLHttpRequest.config = options;
				return $.Deferred().reject(XMLHttpRequest);
			});
		},
		rejected: null
	}], request.interceptors.response);

	let promise = new $.Deferred();
	promise.resolve(options);
	chain.forEach(interceptor => promise = promise.then(interceptor.fulfilled, interceptor.rejected));

	return promise;
};

function resolveFormData(data) {
	data = data || {};

	if (data instanceof FormData) {
		return data;
	}

	const formData = new FormData();
	for (const x in data) {
		if (!data.hasOwnProperty(x)) {
			continue;
		}

		const value = resolveValue(data[x]);

		formData.append(x, value);
	}

	return formData;
}

function resolveValue(value) {
	if (value instanceof File || value instanceof Blob) {
		return value;
	} else if (value === 'object') {
		return JSON.stringify(value);
	}

	return value;
}
